package stardust.product.platform.webc.spi.webservice;


import java.io.IOException;
import java.lang.reflect.Method;
import java.net.UnknownHostException;
import javax.xml.ws.Endpoint;
import stardust.core.java.interceptor.InterceptorFactory;
import stardust.core.java.interceptor.InterceptorTemplateCallback;
import stardust.core.java.reflect.MethodReflect;
import stardust.core.network.protocol.http.support.URI;
import stardust.product.platform.webc.WebcCallback;
import stardust.product.platform.webc.WebcConfig;
import stardust.product.platform.webc.WebcContext;
import stardust.product.platform.webc.WebcException;
import stardust.product.platform.webc.WebcResourceReference;
import stardust.product.platform.webc.annotation.Handler;
import stardust.product.platform.webc.spi.webservice.support.WebServiceServer;


public class WebServiceSupportCallback implements WebcCallback
{

  private Boolean enabledWebService;

  private InterceptorFactory factory;
  private WebServiceInterceptor interceptor;

  private static WebServiceServer webServiceServer;

  public void registerWebService(WebcContext context, final WebcResourceReference reference)
  {
    Object webServiceDelegate;

//    if (1 != 2) return;// TODO 禁用WEB服务支持。
    /*
     * 初始化拦截器工厂。
     */
    if (this.factory == null)
    {
      this.interceptor = new WebServiceInterceptor();
    }
    
    // 为每个拦截方法生成独立的WebService上下文。
    this.factory = InterceptorFactory.createInstance();
    this.factory.setTemplateCallback(new InterceptorTemplateCallback()
    {

      public void onGenerateClass(StringBuffer buffer, Class<?> sourceClass)
      {
        // 增加WebService标注。
        buffer.append("@javax.jws.WebService(targetNamespace=\"").append("/").append("\") ");
      }

      public void onGenerateMethod(StringBuffer buffer, Method method)
      {
        if (method.equals(reference.getTargetMethod()))
        {
          URI uri = new URI(reference.getEntryPoint().value());
          // 增加WebMethod标注。
          buffer.append("@javax.jws.WebMethod(operationName=\"")
                .append(uri.getPath()[uri.getPath().length - 1])
                .append("\") ");
        }
        else
        {
          // 增加WebMethod标注，禁止在WebService中暴露此方法。
          buffer.append("@javax.jws.WebMethod(exclude = true) ");
        }
      }

    });
    
    // 生成并编译WebService的委托代码，返回受拦截的实例。
    webServiceDelegate = this.factory.create(reference.getInstance(), this.interceptor);
    
    /*
     * 初始化HTTP服务器。
     */
    if (WebServiceSupportCallback.webServiceServer == null)
    {
      try
      {
        WebServiceSupportCallback.webServiceServer = new WebServiceServer("/", 9001, 10);
      }
      catch (UnknownHostException e)
      {
        throw new WebcException("无法启用WebService支持，HTTP协议服务器启动失败。", e);
      }
      catch (IOException e)
      {
        throw new WebcException("无法启用WebService支持，HTTP协议服务器启动失败。", e);
      }
    }
    
    // 发布WebService到服务器。
    WebServiceSupportCallback.webServiceServer.publish(reference.getUri(), webServiceDelegate);
  }

  public boolean onBeforeRegisterHandler(WebcContext context, WebcResourceReference reference)
  {
    return true;
  }

  public boolean onAfterRegisterHandler(WebcContext context, WebcResourceReference reference)
  {
    if (this.enabledWebService == null)
    {
//      this.enabledWebService = Boolean.parseBoolean(context.getConfig().getParameter().get(WebcConfig.CFG_WEBSERVICE_ENABLED));
      this.enabledWebService = false;
    }

    if (!this.enabledWebService)
    {
      // 不启用WebService支持，跳过注册。
      return true;
    }

    this.registerWebService(context, reference);

    return true;
  }

}
